#pragma once
#include <vector>
#include <cassert>
#include "Util.hpp"

namespace mylog
{
    #define DEFAULT_BUFFER_SIZE (1 * 1024 * 1024)
    #define THRESHOLD_BUFFER_SIZE (8 * 1024 * 1024)
    #define INCREMENT_BUFFER_SIZE (1 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer()
            : _buffer(DEFAULT_BUFFER_SIZE),
              _reader_idx(0),
              _writer_idx(0){}
        void Push(const char *data, size_t len)
        {

            //动态扩容
            EnsureEnoughSize(len);
            std::copy(data, data+len, &_buffer[_writer_idx]);
            MoveWriter(len);
        }
        // 返回可读数据起始位置
        const char *Begin()
        {
            return &_buffer[_reader_idx];
        }
        // 返回可写数据长度
        size_t WriteableSize()
        {
            return _buffer.size() - _writer_idx;
        }
        // 返回可读数据长度
        size_t ReadableSize()
        {
            return _writer_idx - _reader_idx;
        }
        void MoveReader(size_t len)
        {
            assert(len <= ReadableSize());
            _reader_idx += len;
        }
        // 重置读写位置
        void Reset()
        {
            _writer_idx = 0;
            _reader_idx = 0;
        }
        void Swap(Buffer &buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_writer_idx, buffer._writer_idx);
            std::swap(_reader_idx, buffer._reader_idx);
        }
        bool Empty()
        {
            return _writer_idx == _reader_idx;
        }

    private:
        //扩容
        void EnsureEnoughSize(size_t len)
        {
            if(len < WriteableSize()) return;
            if(_writer_idx + len < THRESHOLD_BUFFER_SIZE)
            {
                _buffer.resize(_buffer.size() * 2 + len);
                return;
            }
            _buffer.resize(_buffer.size() + INCREMENT_BUFFER_SIZE + len);
        }
        // 对写指针进行向后偏移
        void MoveWriter(size_t len)
        {
            assert(len <= WriteableSize());
            _writer_idx += len;
        }
    private:
        std::vector<char> _buffer;
        size_t _reader_idx;
        size_t _writer_idx;
    };
}